import os
import string
import random
from io import BytesIO

from PIL import Image, ImageDraw, ImageFont
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.urls import reverse

from .forms import SignupForm


def index(request):
    return HttpResponse('这是主页')


def signup(request):
    if request.method == 'POST':
        form = SignupForm(request.POST)
        if form.is_valid():
            posted_value = form.cleaned_data.get('captcha', '')
            correct_value = get_session_data(request, 'captcha') or ''
            if posted_value == correct_value:
                print('login success')
                return HttpResponseRedirect(reverse('index'))
            else:
                print('login failed')
                form.add_error('captcha', 'not match')
    else:
        form = SignupForm()
    return render(request, 'app1/signup.html', {'form': form})


def captcha(request):
    """ 生成验证码图片 """
    text = gentext(4)
    # 把验证码内容存到session中
    set_session_data(request, 'captcha', text.lower())
    im = make_image(text)
    imgout = BytesIO()
    im.save(imgout, format='png')
    img_bytes = imgout.getvalue()
    return HttpResponse(img_bytes, content_type='image/png')


def gentext(n=4):
    """ 生成n个字母的随机字符串 """
    chars = string.ascii_letters
    return ''.join([random.choice(chars) for i in range(n)])


def make_image(char):
    """ 生成验证码图片 """
    im_size = (70, 40)
    font_size = 28
    bg = (0, 0, 0)
    offset = (1, 1)
    im = Image.new('RGB', size=im_size, color=bg)
    font_path_relative = 'ubuntu.ttf'
    font_path = os.path.join(settings.BASE_DIR, 'fonts', font_path_relative)
    font = ImageFont.truetype(font_path, font_size)
    draw = ImageDraw.ImageDraw(im)
    draw.text(offset, char, fill='yellow', font=font)
    im = im.transform(im_size, Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR)
    return im


def get_session_id(request):
    name = settings.SESSION_COOKIE_NAME
    sid = request.COOKIES.get(name)
    if sid is None:
        request.session.create()
        sid = request.session.session_key
    return sid


def get_session_data(request, key, sid=None):
    if sid is None:
        sid = get_session_id(request)
    return request.session.get(sid, {}).get(key)


def set_session_data(request, key, data, sid=None):
    if sid is None:
        sid = get_session_id(request)
    sdata = request.session.get(sid, {})
    sdata[key] = data
    request.session[sid] = sdata
